<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\ImportProductAddAction;
use App\Admin\Actions\ShopProduct\ShopProductEditAction;
use App\Admin\Grid\NGrid;
use App\Admin\Grid\Tools\ImportProductTools;
use App\Library\Logic\OperateLogLogic;
use App\Models\ImportProductModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Grid\Tools;

class ImportProductController extends AdminController
{
    protected $title = '上传商品';

    /**
     * grid
     * @return NGrid
     */
    protected function grid(): NGrid
    {
        $grid = new NGrid(new ImportProductModel);
        $grid->model()->orderByDesc('id');
        $grid->column('id', 'ID')->sortable();
        $grid->column('serial_number', __('l.serialNumber'));
        $grid->column('status', __('l.status'))->using([
            0 => '未处理',
            1 => '上传成功',
            2 => '上传失败',
            3 => '取消',
        ]);
        $grid->column('product_ids', '商品ID')->display(function ($column) {
            return !is_null($column) ? implode(',', $column) : null;
        });
        $grid->column('error', '错误信息')->display(function ($column) {
            if (is_null($column)) return null;
            else return $column[0];
        });
        $grid->column('product_upload', '商品信息')->display(function () {
            if (is_null($this->extend)) return null;
            else return view('product.product_upload', [
                'id' => $this->id,
                'extend' => $this->extend,
            ]);
        });
        $grid->column('created_at', __('l.createdAt'));
        $grid->disableCreateButton(false);
        $grid->tools(function (Tools $tools) {
            $tools->append(new ImportProductTools);
        });
        $grid->disableActions(false);
        $grid->actions(function (Actions $action) {
            $action->disableDelete();
            $action->disableEdit();
            $action->disableView();
            if ($action->row->status === 1 && is_null($action->row->product_ids)) $action->add(new ImportProductAddAction);
        });
        return $grid;
    }

    /**
     * form
     * @return Form
     */
    public function form(): Form
    {
        $form = new Form(new ImportProductModel);
        $form->hidden('serial_number');
        $form->file('file', '文件')->rules('mimes:xlsx')->move('xlsx', uniqid() . '.xlsx')->required();
        $form->saving(function (Form $form) {
            $form->serial_number = serialNumber();
        });
        $form->saved(function (Form $form) {
            mq('importProduct', $form->serial_number);
            sleep(2);
        });
        OperateLogLogic::add(Admin::user()->user_id, 'admin.product.import');
        return $form;
    }
}
